/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kylingroup.FileServer;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
/**
 *
 * @author kylin
 */
public class FileServer implements Daemon{
    private Thread myThread; 
    private boolean stopped = false;
    private boolean lastOneWasATick = false;
    
    @Override
    public void init(DaemonContext daemonContext) throws DaemonInitException, Exception {
        String[] args = daemonContext.getArguments(); 
        
        myThread = new Thread(){
            int counter=1;
            private long lastTick = 0;
            
            @Override
            public synchronized void start() {
                FileServer.this.stopped = false;
                super.start();
            }

            @Override
            public void run() {             
                while(!stopped){
                    Date now=new Date();
                    SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
                    System.out.println(counter+". currenttime:"+format.format(now)+" Server thread is running");
                    try{
                        Thread.sleep(60*1000);
                    }catch(InterruptedException e){
                        return;
                    }
                    //long now = System.currentTimeMillis();
                    //if(now - lastTick >= 1000){
                        //System.out.println(!lastOneWasATick ? "tick" : "tock");
                        //lastOneWasATick = !lastOneWasATick;
                        //lastTick = now; 
                    //}
                }
            }
        };
    }

    @Override
    public void start() throws Exception {
        myThread.start();
    }

    @Override
    public void stop() throws Exception {
        stopped = true;
        try{
            myThread.join(1000);
        }catch(InterruptedException e){
            System.err.println(e.getMessage());
            throw e;
        }
    }

    @Override
    public void destroy() {
        myThread = null;
    }   
}